import pickle
import tkinter as tk
import base64
from tkinter import ttk
from tkinter.messagebox import showinfo

from ftp_client_alter_bug.seek.ftp_search import FtpSearch
from ftp_client_alter_bug.seek.win_search import WinSearch
from ftplib import FTP
import tkinter.filedialog as fi
from ftp_client_alter_bug.tree.ftp_tree import FtpTree
from ftp_client_alter_bug.tree.win_tree import WinTree


class TopMenuBar:
    def __init__(self, top_frame, path, win, win_search_path, ftp_list, xuanzhe_win_path):
        self.top_frame = top_frame
        self.path = path
        self.win = win
        self.win_search_path = win_search_path
        self.ftp_list = ftp_list
        self.xuanzhe_win_path = xuanzhe_win_path


    # logo
    def logo(self):
        logo_lable = tk.Label(self.top_frame, text="FTP客户端", font=("华文彩云", 29), fg="green")
        logo_lable.place(x=5, y=10)

    # window目录选择按钮
    def local_mulu(self, win_path, tree):
        # 目录选择按钮的回调函数
        def mulu_button():
            self.xuanzhe_win_path.clear()
            DEF_PATH = ""
            newDir = fi.askdirectory(initialdir=DEF_PATH, title="打开目录").replace('/', '\\')
            print(newDir)
            DEF_PATH = newDir
            if len(newDir) == 0:
                return
            print(DEF_PATH)
            self.xuanzhe_win_path.append(DEF_PATH)
            print(self.xuanzhe_win_path)

            table = tree
            items = table.get_children()
            [table.delete(item) for item in items]

            wintree = WinTree(self.xuanzhe_win_path[0], win_path, tree)
            wintree.show_wenjian()

        mulu_but = tk.Button(self.top_frame, text="选择本地目录", font=("宋体", 13), command=mulu_button, relief="flat")
        mulu_but.place(x=220, y=5)

    # 打开文件按钮
    def open_wenjian(self):
        def open_wenjian_button():
            pass

        open_wenjian_but = tk.Button(self.top_frame, text="选择本地文件", font=("宋体", 13), command=open_wenjian_button, relief="flat")
        open_wenjian_but.place(x=220, y=30)


    # 搜索框和其按钮
    def search_box(self, win_search_name, win_search_tree, ftp_search_path, ftp_list):
        # 本地搜索按钮的回调函数
        def local_search_button():
            try:
                win_search_name.clear()
                win_name = search_entry.get()
                win_search_name.append(win_name)

                table = win_search_tree[0]
                items = table.get_children()
                [table.delete(item) for item in items]
                winsearch = WinSearch(self.xuanzhe_win_path[0], win_name, self.win_search_path, win_search_tree[0])
                winsearch.search()
            except:
                showinfo("错误提示", "本地路径异常！")

        # ftp搜索按钮的回调函数
        def ftp_search_button():
            try:
                win_search_name.clear()
                win_name = search_entry.get()
                win_search_name.append(win_name)

                table = win_search_tree[0]
                items = table.get_children()
                [table.delete(item) for item in items]
                ftpsearch = FtpSearch(ftp_list[0], win_name, ftp_search_path, table)
                ftpsearch.show()
            except:
                showinfo("错误提示", "服务器连接异常！")


        search_entry = tk.Entry(self.top_frame, width="21",  font=("宋体", 15))
        search_entry.place(x=475, y=17)

        window_search = tk.Button(self.top_frame, text="本地搜索", font=("宋体", 15), command=local_search_button, relief="flat")
        window_search.place(x=350, y=17)

        ftp_search = tk.Button(self.top_frame, text="ftp搜索", font=("宋体", 15), command=ftp_search_button, relief="flat")
        ftp_search.place(x=730, y=17)

    # ip,port显示
    def name_ip(self, bieming, ip):
        name = bieming
        name_lable = tk.Label(self.top_frame, text=f"user: {name}", font=("宋体", 13))
        name_lable.place(x=850, y=5)
        ip = ip
        ip_lable = tk.Label(self.top_frame, text=f"ip: {ip}", font=("宋体", 13))
        ip_lable.place(x=1030, y=5)

    # 退出登录按钮
    def exit_login(self, ftp_tree_list, ftp_path, ftp_list):
        def exit_button():
            try:
                self.ftp_list[0].quit()
                table = ftp_tree_list[0]
                items = table.get_children()
                [table.delete(item) for item in items]
                ftptree = FtpTree(ftp_path, ftp_list, ftp_tree_list[0])
                ftptree.xianshi("/")
            except Exception:
                showinfo("退出提示", "已退出登录！")

        try:
            exit_but = tk.Button(self.top_frame, text="退出登录", font=("宋体", 13), command=exit_button, relief="flat")
            exit_but.place(x=1100, y=30)
        except Exception:
            print("已退出登录！")

    # 登录按钮
    def login_in(self, ftp_path, ftp_list, ftp_tree_list):
        def login_in_button():
            wind = tk.Tk()
            wind.geometry("400x370+500+200")
            titile_lab = tk.Label(wind, text="ftp登录", font=("宋体", 19))
            titile_lab.place(x=150, y=30)

            self.ftp_list.clear()

            bieming_lab = tk.Label(wind, text="别名:", font=("宋体", 15))
            bieming_lab.place(x=60, y=90)
            bieming_entry = tk.Entry(wind, font=("宋体", 15))
            bieming_entry.place(x=130, y=90)

            user_name_lab = tk.Label(wind, text="用户名:", font=("宋体", 15))
            user_name_lab.place(x=40, y=130)
            user_name_entry = tk.Entry(wind, font=("宋体", 15))
            user_name_entry.place(x=130, y=130)

            pass_name_lab = tk.Label(wind, text="密码:", font=("宋体", 15))
            pass_name_lab.place(x=60, y=170)
            pass_name_entry = tk.Entry(wind, font=("宋体", 15))
            pass_name_entry.place(x=130, y=170)

            ip_name_lab = tk.Label(wind, text="ip:", font=("宋体", 15))
            ip_name_lab.place(x=80, y=210)
            ip_name_entry = tk.Entry(wind, font=("宋体", 15))
            ip_name_entry.place(x=130, y=210)

            port_name_lab = tk.Label(wind, text="port:", font=("宋体", 15))
            port_name_lab.place(x=60, y=250)
            port_name_entry = tk.Entry(wind, font=("宋体", 15))
            port_name_entry.place(x=130, y=250)

            def d_button():
                self.ftp_list.clear()
                bieming = str(bieming_entry.get())
                user_name = str(user_name_entry.get())
                pass_name = str(pass_name_entry.get())
                ip_name = str(ip_name_entry.get())
                port_name = int(port_name_entry.get())

                try:
                    # 打开被序列化文件
                    with open("../data/usr_info.pickle", "wb") as usr_file:
                        # 用户数据
                        usr_info = [base64.b64encode(bieming.encode("utf-8")),
                                    base64.b64encode(user_name.encode("utf-8")),
                                    base64.b64encode(pass_name.encode("utf-8")),
                                    base64.b64encode(ip_name.encode("utf-8")),
                                    base64.b64encode(str(port_name).encode("utf-8"))]
                        print(usr_info)
                        # 存储(序列化)数据
                        pickle.dump(usr_info, usr_file)
                except FileNotFoundError:
                        print("存储错误")

                self.name_ip(bieming, ip_name)

                self.ftp = FTP()  # 设置变量
                self.ftp.encoding = "GB18030"
                self.ftp.connect(ip_name, port_name)  # 连接的ftp sever和端口
                self.ftp.login(user_name, pass_name)  # 连接的用户名，密码
                # self.ftp.encoding = 'GB18030'


                self.ftp_list.append(self.ftp)

                table = ftp_tree_list[0]
                items = table.get_children()
                [table.delete(item) for item in items]
                ftptree = FtpTree(ftp_path, ftp_list, ftp_tree_list[0])
                ftptree.xianshi("/")

                wind.destroy()


            d_but = tk.Button(wind, text="登=======================录", font=("宋体", 15), command=d_button)
            d_but.place(x=60, y=310)


            wind.mainloop()



        login_in_but = tk.Button(self.top_frame, text="登录", font=("宋体", 13), command=login_in_button, relief="flat")
        login_in_but.place(x=850, y=30)

    # 历史登录
    def lishi_login_in(self, ftp_path, ftp_list, ftp_tree_list):
        def lishi_login_button():
            self.ftp_list.clear()
            try:
                # 打开被序列化文件，会自动创建此文件
                with open("../data/usr_info.pickle", "rb+") as usr_file:
                    # 读取被序列化的文件
                    global usr_info
                    usr_info = pickle.load(usr_file)
                    print(usr_info)
            except FileNotFoundError:
                    print("读取错误")

            self.name_ip(base64.b64decode(usr_info[0]).decode("utf-8"),
                         base64.b64decode(usr_info[3]).decode("utf-8"))

            self.ftp = FTP()  # 设置变量
            self.ftp.connect(base64.b64decode(usr_info[3]).decode("utf-8"),
                             int(base64.b64decode(usr_info[4]).decode("utf-8")))  # 连接的ftp sever和端口
            self.ftp.login(base64.b64decode(usr_info[1]).decode("utf-8"),
                           base64.b64decode(usr_info[2]).decode("utf-8"))  # 连接的用户名，密码
            self.ftp.encoding = 'GB18030'

            self.ftp_list.append(self.ftp)

            table = ftp_tree_list[0]
            items = table.get_children()
            [table.delete(item) for item in items]
            ftptree = FtpTree(ftp_path, ftp_list, ftp_tree_list[0])
            ftptree.xianshi("/")

        lishi_login_but = tk.Button(self.top_frame, text="历史登录", font=("宋体", 13), command=lishi_login_button, relief="flat")
        lishi_login_but.place(x=950, y=30)